import request from '@/utils/request';
import { AxiosPromise } from 'axios';
import { PageQuery, PageResult } from '@/types/common';

/**
 * 订单查询对象
 */
export interface OrderQuery extends PageQuery {
  orderNo?: string;
  userId?: number;
  projectName?: string;
  hospitalName?: string;
  orderStatus?: string;
  loanStatus?: string;
  beginTime?: string;
  endTime?: string;
}

/**
 * 订单业务对象
 */
export interface OrderForm {
  orderId?: number;
  orderNo?: string;
  userId?: number;
  projectId: number;
  projectName?: string;
  projectPrice?: number;
  hospitalId: number;
  planId?: number;
  periods: number;  // 分期期数（主字段）
  interestRate?: number;  // 月利率（主字段）
  monthlyAmount?: number;  // 月供金额（主字段）
  totalAmount?: number;
  paidAmount?: number;  // 已还金额
  unpaidAmount?: number;  // 待还金额
  downPayment: number;
  loanAmount?: number;
  totalInterest?: number;
  totalRepayment?: number;
  orderStatus?: string;
  loanStatus?: string;
  loanTime?: string;
  repaymentDay?: number;  // 还款日
  firstRepaymentDate?: string;  // 首次还款日期
  lastRepaymentDate?: string;  // 最后还款日期
  rejectReason?: string;  // 拒绝原因
  cardId: number;
  auditRemark?: string;
  contractId?: number;
}

/**
 * 订单视图对象
 */
export interface OrderVO {
  orderId: number;
  orderNo: string;
  userId: number;
  projectId: number;
  projectName: string;
  projectPrice: number;
  projectImage: string;  // 扩展字段
  hospitalId: number;
  hospitalName: string;  // 扩展字段
  hospitalAddress: string;  // 扩展字段
  hospitalPhone: string;  // 扩展字段
  planId: number;
  periods: number;  // 分期期数（主字段）
  interestRate: number;  // 月利率（主字段）
  monthlyAmount: number;  // 月供金额（主字段）
  totalAmount: number;
  paidAmount: number;  // 已还金额
  unpaidAmount: number;  // 待还金额
  downPayment: number;
  loanAmount: number;
  totalInterest: number;
  totalRepayment: number;
  orderStatus: string;
  orderStatusText: string;  // 扩展字段：状态文本
  loanStatus: string;
  loanStatusText: string;  // 扩展字段：放款状态文本
  loanTime: string;
  repaymentDay: number;  // 还款日（每月几号）
  firstRepaymentDate: string;  // 首次还款日期
  lastRepaymentDate: string;  // 最后还款日期
  overdueDays: number;  // 逾期天数
  overdueFee: number;  // 逾期费用
  earlyRepayment: number;  // 是否提前还款
  earlyRepaymentTime: string;  // 提前还款时间
  rejectReason: string;  // 拒绝原因
  cardId: number;
  cardNo: string;  // 扩展字段：银行卡号（脱敏）
  bankName: string;  // 扩展字段：银行名称
  auditTime: string;
  auditRemark: string;
  contractId: number;
  remark: string;
  createTime: string;
}

/**
 * 审核订单请求对象
 */
export interface AuditOrderRequest {
  orderId: number;
  orderStatus: string; // 1-审核通过, 2-审核拒绝
  auditRemark?: string;
}

/**
 * 订单统计对象
 */
export interface OrderStatistics {
  total: number;
  auditing: number;
  contract_signing: number;
  disbursing: number;
  repaying: number;
  completed: number;
}

/**
 * 查询订单列表
 */
export function listOrder(query: OrderQuery): AxiosPromise<PageResult<OrderVO>> {
  return request({
    url: '/admin/beauty/order/list',
    method: 'get',
    params: query
  });
}

/**
 * 查询订单详细
 */
export function getOrder(orderId: number): AxiosPromise<OrderVO> {
  return request({
    url: '/admin/beauty/order/' + orderId,
    method: 'get'
  });
}

/**
 * 修改订单
 */
export function updateOrder(data: OrderForm): AxiosPromise<void> {
  return request({
    url: '/admin/beauty/order',
    method: 'put',
    data: data
  });
}

/**
 * 删除订单
 */
export function delOrder(orderIds: number | number[]): AxiosPromise<void> {
  return request({
    url: '/admin/beauty/order/' + orderIds,
    method: 'delete'
  });
}

/**
 * 审核订单
 */
export function auditOrder(data: AuditOrderRequest): AxiosPromise<void> {
  return request({
    url: '/admin/beauty/order/audit',
    method: 'post',
    data: data
  });
}

/**
 * 批量审核订单
 */
export function batchAuditOrder(data: AuditOrderRequest, orderIds: number[]): AxiosPromise<void> {
  return request({
    url: '/admin/beauty/order/batchAudit',
    method: 'post',
    params: { orderIds },
    data: data
  });
}

/**
 * 确认放款
 */
export function confirmLoan(orderId: number): AxiosPromise<void> {
  return request({
    url: '/admin/beauty/order/confirmLoan/' + orderId,
    method: 'post'
  });
}

/**
 * 批量确认放款
 */
export function batchConfirmLoan(orderIds: number[]): AxiosPromise<void> {
  return request({
    url: '/admin/beauty/order/batchConfirmLoan',
    method: 'post',
    data: orderIds
  });
}

/**
 * 取消订单
 */
export function cancelOrder(orderId: number): AxiosPromise<void> {
  return request({
    url: '/admin/beauty/order/cancel/' + orderId,
    method: 'post'
  });
}

/**
 * 获取订单统计
 */
export function getOrderStatistics(userId?: number): AxiosPromise<OrderStatistics> {
  return request({
    url: '/admin/beauty/order/statistics',
    method: 'get',
    params: userId ? { userId } : {}
  });
}

/**
 * 导出订单
 */
export function exportOrder(query: OrderQuery): AxiosPromise<Blob> {
  return request({
    url: '/admin/beauty/order/export',
    method: 'post',
    params: query,
    responseType: 'blob'
  });
}

/**
 * 风控审核请求对象
 */
export interface RiskAuditRequest {
  orderId: number;
  passed: boolean;  // true-通过, false-拒绝
  riskScore?: number;  // 风控评分
  auditRemark?: string;  // 审核备注
  rejectReason?: string;  // 拒绝原因（当passed=false时必填）
}

/**
 * 医院审核请求对象
 */
export interface HospitalAuditRequest {
  orderId: number;
  passed: boolean;  // true-通过, false-拒绝
  surgeryDate?: string;  // 手术日期（当passed=true时必填）
  auditRemark?: string;  // 审核备注
  rejectReason?: string;  // 拒绝原因（当passed=false时必填）
}

/**
 * 审核日志对象
 */
export interface OrderAuditLog {
  logId: number;
  orderId: number;
  auditType: string;  // RISK-风控审核, HOSPITAL-医院审核
  auditResult: string;  // PASS-通过, REJECT-拒绝
  auditRemark: string;
  auditorId: number;
  auditorName: string;
  createTime: string;
}

/**
 * 风险评分结果
 */
export interface RiskScoreResult {
  orderId: number;
  riskScore: number;  // 风险评分
  scoreDetails: {
    baseScore: number;
    idVerified: boolean;
    phoneVerified: boolean;
    bankcardVerified: boolean;
    hasOverdue: boolean;
    overdueCount: number;
  };
}

/**
 * 风控审核
 */
export function riskAudit(data: RiskAuditRequest): AxiosPromise<void> {
  return request({
    url: '/admin/beauty/order/riskAudit',
    method: 'post',
    data: data
  });
}

/**
 * 医院审核
 */
export function hospitalAudit(data: HospitalAuditRequest): AxiosPromise<void> {
  return request({
    url: '/admin/beauty/order/hospitalAudit',
    method: 'post',
    data: data
  });
}

/**
 * 获取订单审核日志
 */
export function getAuditLogs(orderId: number): AxiosPromise<OrderAuditLog[]> {
  return request({
    url: '/admin/beauty/order/auditLogs/' + orderId,
    method: 'get'
  });
}

/**
 * 计算风险评分
 */
export function calculateRiskScore(orderId: number): AxiosPromise<RiskScoreResult> {
  return request({
    url: '/admin/beauty/order/calculateRiskScore/' + orderId,
    method: 'get'
  });
}
